package zw_1_100.zw_19_删除链表的倒数第N个结点;


/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {

    class ListNode {
        public int val; // 节点的保存的内容
        public ListNode next = null;  //节点的引用，指向下一节点

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        int len = 0;
        ListNode ans = new ListNode(0);
        ans.next=head;//头节点指向这个链表
        ListNode l1 = ans;
        while (l1.next!=null){
            len++;
            l1 = l1.next;
        }
        ListNode temp = ans;
        for (int i = 1; i<len-n+1; i++) {
            temp = temp.next;
        }
        temp.next = temp.next.next;
        return ans.next;
    }


//    public ListNode removeNthFromEnd(ListNode head, int n) {
//        ListNode pre = new ListNode(0);
//        pre.next = head;
//        ListNode start = pre, end = pre;
//        while (n != 0) {
//            start = start.next;
//            n--;
//        }
//        while (start.next != null) {
//            start = start.next;
//            end = end.next;
//        }
//        end.next = end.next.next;
//        return pre.next;
//    }
}
